#include "query.h"

#include <QFile>
#include <QTextStream>
#include <QCoreApplication>
#include <QDebug>

Tagger * Query::tagger = new Tagger();
PlWordNetDAO Query::wordnet = PlWordNetDAO();

Query::Query(const QString &filePath, const QStringList &stoplist, int resultNumber) :
    resultNumber(resultNumber)
{
    QFile file(filePath);
    file.open(QIODevice::ReadOnly);
    QTextStream in(&file);
    QString line = " "+in.readLine()+" ";
    origQuery = line;
    foreach (const QString &stopword, stoplist)
    {
        line.replace(QString(" %1 ").arg(stopword)," ",Qt::CaseInsensitive);
    }
    line=line.trimmed();
    query = line;
    while(! (line = in.readLine()).isEmpty())
        docs << line;
    file.close();
}

Query::Query(const QString &query, const QStringList &stoplist) : origQuery(query), query(query), resultNumber(20)
{
    foreach (const QString &stopword, stoplist)
    {
        this->query.replace(QString(" %1 ").arg(stopword), " ", Qt::CaseInsensitive);
    }
    this->query = this->query.trimmed();
}

QUrl Query::getQueryUrl()
{
    //QString url("http://localhost:9200/docs/wiki/_search?q=content:");
    QString url("http://localhost:9200/docs/wiki/_search?source=");
    this->tagQuery();
    //qDebug() << lexems;
    QString mid(query.replace("?",""));
    mid+=" ";
    foreach(const QString &lexem, lexems){
        QStringList synonyms(wordnet.findSynonyms(lexem));
        if(synonyms.isEmpty())
            mid += lexem + " ";
        else
            mid += synonyms.join(" ") + " ";
    }
    //mid.remove(mid.size() - 3, 3);
    //mid.replace(" ", "%20");


    url += getQueryJson(mid);
    url += QString("&size=") + QString::number(resultNumber);
   // qDebug() << url;
    return QUrl(url);
}

QString Query::getQueryJson(QString &mid)
{
    QString json("{\"query\":{\"query_string\":{\"fields\":[\"title^5\",\"content\",\"base\"],\"query\":\"");
    json.append(mid);
    json.append("\"}}}");

    return json;
}

void Query::tagQuery()
{
    QTemporaryFile *fileForTagging;
    fileForTagging = new QTemporaryFile;
    QTextStream out(fileForTagging);
    fileForTagging->open();
    out << QString(query).remove("?");
    fileForTagging->close();
    tagger->tagFile(fileForTagging->fileName());

    while(tagger->isTagging()){
        qApp->processEvents();
    }

    lexems = tagger->lexemQuery();

    delete fileForTagging;
}
